<?php

/**
 * Created by PhpStorm.
 * User: wyr
 * Date: 14-10-8
 * Time: 下午10:14
 */
class Controller_Wwwmall3_Order extends Controller_Wwwmall3_Abstract
{
    public function indexAction()
    {
        //$this->openDebug();
        //Service_Order::orderPushQueue('2017072716360716912',4);
        //Service_Location::getAddressFromXY('112.893358','28.214067');
        //Service_Template::set_tpl_msg('2017071417583242420');
        /*       $this->openDebug();*/
        /*require_once(APP_ROOT . 'lib/weixin/WeixinChat.class.php');
        $options = array(
            'token' => FConfig::get('wechat.token'),
            'appid' => FConfig::get('wechat.appid'),
            'appsecret' => FConfig::get('wechat.appsecret'),
        );
        $weixin = new WeixinChat($options);
        $openid = 'oQBIz1AMNlrzkAOUq0qado6_u9SU';
        $user_wechat_scan_data = Service_User::getUserInfo($openid);//根据openid获取用户信息
        $userInfo = $weixin->getUserInfo($openid);
        var_dump($userInfo);
        $result = array(
            'openid' => $openid,
            'nickname' => $userInfo['nickname'],
            'sex' => $userInfo['sex'],
            'city' => $userInfo['city'],
            'province' => $userInfo['province'],
            'headimgurl' => $userInfo['headimgurl'],
            'subscribe' => 1,
            'subscribe_time' => $userInfo['subscribe_time'],
            'last_operation_time' => time() + 60 * 60 * 24 * 2,
        );
        Service_User::saveUser($result);*/
    }
    //tanghui
    public function submitAction()
    {
        //获取当前用户信息
        global $_F;
        $uid = $_F['uid'];
        //拿用户最新一单
//        $orderModel = new FTable("orders",'','xhs_master');
//        $orderInfo=$orderModel->where(['uid'=>$uid,'status'=>1])->order('auto_id desc')->find();
//        if($orderInfo){
//            $difft=time()-strtotime($orderInfo['create_time']);
//            if($difft< 600) {
//                echo "<script>";
//                echo "location='/pay/wx?oid=" . $orderInfo['auto_id'] . "';";
//                echo "</script>";
//                return false;
//            }
//        }
        //$uid=6;
        //获取用户收货地址
        $userAddress = new FTable("user_address",'','xhs_slave');
        $userAddressInfo = $userAddress->where(array('uid' => $uid))->order("is_default asc")->find();
        //print_r($userAddressInfo);exit;
        //计算最近的商户，拿到商户信息
        $order_str = "create_time desc";
        if (!empty($userAddressInfo['lat']) && !empty($userAddressInfo['lng'])) {
            $order_str = " ACOS(SIN((" . $userAddressInfo['lat'] . "  * 3.1415) / 180 ) *SIN((y * 3.1415) / 180 ) +COS((" . $userAddressInfo['lat'] . " * 3.1415) / 180 ) * COS((y * 3.1415) / 180 ) *COS((" . $userAddressInfo['lng'] . " * 3.1415) / 180 - (x * 3.1415) / 180 ) ) * 6380  asc";
        }
        $chain_shop = new FTable('chain_shop','','xhs_slave');
        $ctime= date("H:i:s");
        $shopInfo = $chain_shop->where(array('status'=>1,'start_work_time'=>'lte '.$ctime,'stop_work_time'=>'gte '.$ctime))->order($order_str)->find();


        if(empty($shopInfo)){
            $shopInfo1 = $chain_shop->where(array('status'=>1))->order($order_str)->find();

            $store_close_words = $this->config['store_close_words'];
            $store_close_words = str_replace('{$start_time}',substr($shopInfo1['start_work_time'],0,5),$store_close_words);
            $store_close_words = str_replace('{$end_time}',substr($shopInfo1['stop_work_time'],0,5),$store_close_words);

            //$this->error("非营业时间不能下单(营业时间 {$stime} — {$etime})", '/');return false;
            $this->assign("msg", $store_close_words);
            $this->assign("url", "/");
            $this->display("err");
            return false;
        }
        $this->assign("shop_info", $shopInfo);
        //$userAddressInfo =$userAddress->leftJoin('province','p','p.provinceID = ua.province')->where(['uid'=>$uid])->order("is_default asc")->find();
        //获取配送费
        $detailAddress=$userAddressInfo['province'].$userAddressInfo['city'].$userAddressInfo['county'].$userAddressInfo['address'].$userAddressInfo['housemember'];
        $res=Service_ApiBaidu::getShipping(array('r_address'=>$detailAddress
                                    ,'r_lat'=>empty($userAddressInfo['lat'])?0:$userAddressInfo['lat']
                                    ,'r_lng'=>empty($userAddressInfo['lng'])?0:$userAddressInfo['lng']
                                    ,'s_address'=>$shopInfo['address']
                                    ,'s_lat'=>empty($shopInfo['y'])?0:$shopInfo['y']
                                    ,'s_lng'=>empty($shopInfo['x'])?0:$shopInfo['x']

        ));
        //print_r($res);exit;
        $shipping=5; //固定5元
        $rshipping=$res->data->expense;
        $distance=$res->data->dist;
        $pid=$res->data->pid;
        if($distance<=3){
            $rshipping=10;
        }else{
            $rshipping=10+(ceil($distance)-3);
        }
        //print_r($res);exit;
        //获取购物车信息
        $cart_list = Service_Goods::getCartGoods();
        //print_r($cart_list);exit;
        $new_cart_list=[];
        if (!$cart_list) {
            //$this->error('购物车为空', '/');return false;
            $this->assign("msg", "购物车为空");
            $this->assign("url", "/");
            $this->display("err");
            return false;
        } else {//算总价
            $price = 0;
            //$shipping = 0;
            $postage = 0;//邮费
            //获取限制费用
            $restrict = 50;

            foreach ($cart_list as $cart) {
                $price += ($cart['price_new'] * $cart['cart_num']);
                $postage += $cart['freight'];
                $spec_list=json_decode($cart['spec_list'],true);
                //print_r($cart['spec_list']);exit;
                $nspecList=[];
                foreach($spec_list as $s){
                    $nspecList[]= json_decode($s,true);
                }
                $cart['spec_list'] = $nspecList;
                //print_r($nspecList);exit;
                $new_cart_list[]=$cart;
            }
            //判断是否大于指定购买费用
            if ($price < $restrict) {
                $this->assign("is_price_over", false);
            } else {
                $this->assign("is_price_over", true);
            }
            $this->assign("money_ex", array('rshipping'=>$rshipping,'shipping' => $shipping,'pid'=>$pid,'distance'=>$distance, 'price' => $price, 'postage' => $postage, 'paymoney' => $shipping + $price ));

        }

        $reduce_money = 0;
        $firstOrder = Service_Order::firstOrder($_F['uid']);
        if($firstOrder){
            $reduce_money = $this->config['first_reduce_money'];
        }else{
            $reduce_money = $this->fullReduce($price);
        }
        $this->assign('firstOrder',$firstOrder);
        $this->assign('reduce_money',$reduce_money);

        Service_VisitLog::add($_F['uid'],2);

        //当前时间
        $currentTime = date("Y-m-d H:i:s");
        $this->assign("uid", $uid);
        $this->assign("current_time", $currentTime);
        $this->assign("cart_list", $new_cart_list);
        $this->assign("user_address", $userAddressInfo);
        $this->display("Submit_order1");
    }

    public function saveAction()
    {
        global $_F;
        $uid = $_F['uid'];
        //拿用户最新一单
        $orderModel = new FTable("orders",'','xhs_master');
        $orderInfo=$orderModel->where(['uid'=>$uid,'status'=>1])->order('auto_id desc')->find();

        $addressId = FRequest::getPostInt("aid");
        $price = FRequest::getPostInt('paymoney');
        $uid = FRequest::getPostInt('uid');
        $shipping = FRequest::getPostInt('shipping');
        $shop_id = FRequest::getPostInt('shop_id');
        $remark = FRequest::getPostString('remark');
        $dis = FRequest::getPostString('dis');
        $pid = FRequest::getPostString('pid');
        $rshipping = FRequest::getPostString('rshipping');
        //获取购物车信息
        $cart_list = Service_Goods::getCartGoods();
        $order_id = Service_Order::getOrderNo();
        if(empty($cart_list)){
            if ($orderInfo) {
                $difft = time() - strtotime($orderInfo['create_time']);
                if ($difft < 600) {
                    //echo "<script>";
                    //echo "location='/pay/wx?oid=" . $orderInfo['auto_id'] . "';";
                    //echo "</script>";
                    FResponse::output(array('code' => 301, 'url' => '/pay/wx?oid=' . $orderInfo['auto_id']));
                    return false;
                }
            }
            $this->assign("msg", "购物车为空");
            $this->assign("url", "/");
            $this->display("err");
        }
        $peizhi=Service_Order::Peizhi();

        if($dis>$peizhi['distance']){
            Service_VisitLog::add($_F['uid'],3,'',$dis);
            FResponse::output(array('code'=>500,'msg'=>$peizhi['cue_words'],'url'=>'/'));return false;
        }

        $reduce_money = 0;
        $firstOrder = Service_Order::firstOrder($_F['uid']);
        if($firstOrder){
            $reduce_money = $this->config['first_reduce_money'];
        }else{
            $reduce_money = $this->fullReduce($price);
        }

        //获取商家信息
        $shopModel= new FTable('chain_shop','','xhs_slave');
        $shop_info=$shopModel->where(array('id'=>$shop_id))->find();
        //获取用户地址
        $userAddress = new FTable("user_address",'','xhs_slave');
        $userAddressInfo = $userAddress->where(array('auto_id' => $addressId))->find();
        $orderModel = new FTable("orders",'','xhs_master');
        $orderModel->insert(array(
            'uid' => $uid,
            'o_id' => $order_id,
           // 'price' => $price - $shipping - $reduce_money,
            'price' => $price - $shipping,
            'send_price'=>$shipping,
            'real_send_price'=>$rshipping,
            'pay_price' => $price-$reduce_money,
            'youhui_price' => $reduce_money,
            'shop_id' => $shop_id,
            'shop_phone'=>$shop_info['phone'],
            'contact' => $userAddressInfo['contact'],
            'phone' => $userAddressInfo['phone'],
            'city' => $userAddressInfo['city'],
            'county' => $userAddressInfo['county'],
            'province' => $userAddressInfo['province'],
            'address' => $userAddressInfo['address'].$userAddressInfo['housemember'],
            'lat' => $userAddressInfo['lat'],
            'lng' => $userAddressInfo['lng'],
            'sex' => $userAddressInfo['sex'],
            'remark' => $remark,
            'dis'=>$dis,
            'api_pid'=>$pid,
            'pay_time' => '1970-01-01 00:00:00',
        ));
        $oid=$orderModel->lastInsertId();
        $orderProModel = new FTable("orders_product",'','xhs_master');
        $profit = 0;
        $purchase_price=0;
        foreach ($cart_list as $cart) {
            $profit+=($cart['profit']*$cart['cart_num']);
            $purchase_price += ($cart['purchase_price']*$cart['cart_num']);
            $orderProModel->insert(array(
                'o_id' => $order_id,
                'gid' => $cart['gid'],
                'pid' => $cart['pid'],
                'spec_list' => $cart['spec_list'],
                'img2' => $cart['img2'],
                'price_old' => $cart['price_old'],
                'price_new' => $cart['price_new'],
                'purchase_price' => $cart['purchase_price'],
                'title'=>$cart['title'],
                'unit'=>$cart['unit'],
                'profit' => $cart['profit'],
                'weight' => $cart['weight'],
                'paynum' => $cart['cart_num'],
            ));
        }
        $profit=$price - $reduce_money-$purchase_price-$rshipping;
        $orderModel->update1(array('profit'=>$profit,'purchase_price'=>$purchase_price),array('auto_id'=>$oid));

        Service_VisitLog::add($_F['uid'],4);

        Service_Goods::clearCart();
        //跳到我的订单页面
        //echo "ok";
       // $this->success("订单提交成功","/order/myorder");
        FResponse::output(array('code'=>200,'url'=>'/pay/wx?oid='.$oid));
//        echo "<script>";
//        echo "location='/pay/wx?oid=".$oid."';";
//        echo "</script>";
    }

    public function myorderAction()
    {
        //获取当前用户信息
        global $_F;
        $uid = $_F['uid'];
        $status=FRequest::getString('status');
        if($status) {
            $this->assign("status_name", Service_Order::getOrderStatusName($status));
            $this->assign("status_flag", $status);
        }else{
            $this->assign("status_name", "全部");
            $this->assign("status_flag", 0);
        }
        //$uid=1;
        $orderModel = new FTable("orders",'','xhs_slave');
        $oProductModel = new FTable("orders_product",'','xhs_slave');
        $outputOrder=[];
        if($status) {
            $orders = $orderModel->where(array('uid' => $uid, 'status' => $status))->order("create_time desc")->select();
        }else{
            $orders = $orderModel->where(array('uid' => $uid))->order("create_time desc")->select();
        }
        if($orders){
            foreach($orders as $key=>$o){
                //1待付款，2待接单，3商家已接单，4派送中, 5已完成, 6已取消


                $oProducts=$oProductModel->where(array('o_id'=>$o['o_id']))->select();
                if(empty($oProducts)){
                    continue;
                }
                $outputOrder[$key]=$o;
                //$oProducts['spec_list']= json_decode($oProducts['spec_list'],true);
                //print_r($oProducts['spec_list']);
                $outputOrder[$key]['products']=$oProducts;
                //$outputOrder[$key]['products']['spec_list'] = json_decode($oProducts['spec_list']);

               // ["{\"id\":1,\"name\":\"规格\",\"value\":\"中杯\"}","{\"id\":2,\"name\":\"口味\",\"value\":\"芒果\"}"]
                if($status == 3 ||$status==4){
                    //获取店铺信息
                    $shopModel = new FTable("chain_shop",'','xhs_slave');
                    $shopInfo=$shopModel->where(array('id'=>$o['shop_id']))->find();
                    $outputOrder[$key]['shopInfo']=$shopInfo;
                }

            }
        }



        $this->assign("order_list", $outputOrder);

        $this->display("my_order");
    }

    public function detailAction()
    {

        global $_F;
        $uid = $_F['uid'];
        //$uid=1;
        $orderId=FRequest::getString("oid");
        $orderModel = new FTable("orders",'','xhs_slave');
        $order=$orderModel->where(array('o_id'=>$orderId,'uid'=>$uid))->find();
        $order['status_name']=Service_Order::getOrderStatusName($order['status']);
        $this->assign("order", $order);
        $this->display("order_status");
    }

    public function cancelAction()
    {
        $orderId=FRequest::getPostString("oid");
        $orderModel = new FTable("orders",'','xhs_master');
        $orderModel->update(array('status'=>6),array('o_id'=>$orderId));
        FResponse::output(array('code'=>200));
        //$this->success("取消成功","/order/myorder");
    }

    public function againAction()
    {
        $orderId=FRequest::getString("oid");
        $oProductModel = new FTable("orders_product",'','xhs_slave');
        $orderProduct=$oProductModel->where(array('o_id'=>$orderId))->select();
        if($orderProduct){
            foreach($orderProduct as $p){
                Service_Goods::updateCart($p['pid'],$p['paynum']);
            }
        }
        $this->success("下单成功","/order/submit");
    }

    public function updateAction()
    {
        $gid = FRequest::getPostInt("gid");
        $num = FRequest::getPostInt("num");
        Service_Goods::updateCart($gid, $num);
        FResponse::output(['code' => 200]);
    }
}